<template>
  <el-form ref="userForm" :model="user" :rules="rules" label-width="100px">
    <el-form-item label="旧密码" prop="oldPassword" required>
      <el-input v-model="user.oldPassword" show-password placeholder="请输入旧密码" />
    </el-form-item>
    <el-form-item label="新密码" prop="newPassword">
      <el-input v-model="user.newPassword" show-password placeholder="请输入新密码" />
    </el-form-item>
    <el-form-item label="确认密码" prop="confirmPassword">
      <el-input v-model="user.confirmPassword" show-password placeholder="请再次输入新密码" />
    </el-form-item>
    <el-form-item>
      <el-button @click="$router.go(-1)">返回</el-button>
      <el-button @click="resetForm('userForm')">重置</el-button>
      <el-button type="primary" @click="submitForm('userForm')">保存</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import userApi from '@/api/sys/user'

export default {
  data() {
    return {
      user: {
        id: 1,
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      rules: {
        newPassword: [
          { required: true, message: '新密码不能为空', trigger: 'blur' },
          { min: 6, message: '密码不能少于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '确认密码不能为空', trigger: 'blur' },
          { validator: this.validateConfirmPassword, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 确认密码
    validateConfirmPassword(rule, value, callback) {
      if (value !== this.user.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    },

    // 提交
    submitForm(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          userApi.updatePassword(this.user).then(() => {
            this.$message.success('修改成功')
          })
        }
      })
    },

    // 重置
    resetForm(form) {
      this.$refs[form].resetFields()
      this.getUserInfo()
    }
  }
}
</script>
